package com.shiliao.app.activity.personal.ui;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.View;

import com.shiliao.app.R;
import com.shiliao.app.dialog.OpenLocationDialog;
import com.shiliao.app.weight.ActionBarView;
import com.shiliao.app.weight.CircleImageView;
import com.shiliao.app.weight.FileUtils;
import com.shiliao.app.weight.ImageUtils;
import com.yimei.framework.base.ui.BaseActivity;
import com.yimei.framework.util.LogUtil;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by yinzhiqiang on 2017/10/28.
 */

public class InforMationActivity extends BaseActivity {

    public final static int RESULT_PICK_FROM_CAMERA = 1;
    public final static int RESULT_SELECT_PICTURE = 2;
    private static final int PHOTO_REQUEST_CUT = 3;// 结果
    private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
    public static final int AUTO_REQUEST = 4;

    @BindView(R.id.mine_touxiang)
    CircleImageView myImage;

    @BindView(R.id.actionbar)
    ActionBarView barView;

    String tempFilePath = "";
    private long time;
    private File tempFile;
    private Bitmap bitmap;

    @Override
    public int getLayoutId() {
        return R.layout.activity_information;
    }

    @Override
    public void initView() {
        super.initView();
        barView.setTitles("设置个人信息");
        barView.setBackClick(this);
        barView.getBackView().setVisibility(View.VISIBLE);
    }

    @OnClick(R.id.information_name)
    public void setNick() {
        Intent intent = new Intent(this, SeetingInfoActivity.class);
//        intent.putExtra("from", "nick");
        startActivity(intent);
//        toActivity(new Intent(this,SeetingInfoActivity.class));
    }

/*    @OnClick(R.id.rl_setphonenumber)
    public void setPhoneNumber() {
        Intent intent = new Intent(this, SeetingInfoActivity.class);
        intent.putExtra("from", "number");
        startActivity(intent);
//        toActivity(new Intent(this,SeetingInfoActivity.class));
    }*/

    public static Handler handler = new Handler();

    public static void postDelay(Runnable r) {
        handler.postDelayed(r, 300);
    }

    @OnClick(R.id.post_pic)
    public void setPic() {
        /*
        final MyPicDialog dianlog = new MyPicDialog(this);
        dianlog.show(false);
        dianlog.setPaiPic(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                postDelay(new Runnable() {
                    @Override
                    public void run() {
                        try {
//                            if (ActivityCompat.checkSelfPermission(getApplicationContext(),
//                                    Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
//                                openPermission();
//                            } else {
                            pickImageFromCamera();
//                            }
                        } catch (Exception e) {
                            openPermission();
//                            LogUtil.e("huihui...");
//                            return;
                        }
                        dianlog.dismiss();

                    }
                });
            }
        });
        dianlog.setCamera(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                postDelay(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent = new Intent(
                                Intent.ACTION_PICK);
                        intent.setType("image/*");
                        toActivity(intent, RESULT_SELECT_PICTURE);
                        dianlog.dismiss();
                    }
                });
            }
        });
        dianlog.setCancle(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dianlog.dismiss();
            }
        });
        */
        showToast("头像设置功能暂未支持");
    }

    private void pickImageFromCamera() {
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        // 判断存储卡是否可以用，可用进行存储
        if (hasSdcard()) {
            time = System.currentTimeMillis();
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
                    Environment.getExternalStorageDirectory(), time
                    + PHOTO_FILE_NAME)));
        }
        toActivity(intent, RESULT_PICK_FROM_CAMERA);
    }

    /**
     * 打开相机权限
     */
    public void openPermission() {

        final OpenLocationDialog dialog = new OpenLocationDialog(this);
        dialog.show(false);
        dialog.setTitle("请授予相机权限");
        dialog.setCancle(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.setComfirn(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getAppDetailSettingIntent();
                dialog.dismiss();
            }
        });

    }

    private void getAppDetailSettingIntent() {
        try {
            Intent localIntent = new Intent();
            localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (Build.VERSION.SDK_INT >= 9) {
                localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                localIntent.setData(Uri.fromParts("package", getApplicationContext().getPackageName(), null));
            } else if (Build.VERSION.SDK_INT <= 8) {
                localIntent.setAction(Intent.ACTION_VIEW);
                localIntent.setClassName("com.android.settings",
                        "com.android.settings.InstalledAppDetails");
                localIntent.putExtra("com.android.settings.ApplicationPkgName",
                        getApplicationContext().getPackageName());
            }
            toActivity(localIntent);
        } catch (Exception e) {
            LogUtil.e(e.getMessage());
        }
    }

    // 判断是否有sd卡
    private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent it) {
        if (requestCode == RESULT_PICK_FROM_CAMERA) {
            if (hasSdcard()) {

                tempFile = new File(Environment.getExternalStorageDirectory(),
                        time + PHOTO_FILE_NAME);
                String filePath = tempFile.getAbsolutePath();
                LogUtil.e("...tempFile...." + filePath);

                if (!tempFile.exists() || tempFile.length() == 0) {
                    showToast("无法加载此图片");
                    return;
                }
                crop(Uri.fromFile(tempFile));
                if (filePath != null && FileUtils.isFileExist(filePath) != null) {
                    tempFilePath = filePath;

                }
            }

        } else if (requestCode == RESULT_SELECT_PICTURE) {
            if (it == null) {
                return;
            }

            String filePath = FileUtils.getAbsoluteImagePath(this, it.getData());
            crop(it.getData());
            if (filePath != null && FileUtils.isFileExist(filePath) != null) {
                tempFilePath = filePath;
            }
        } else if (requestCode == PHOTO_REQUEST_CUT) {
            if (it != null) {
                bitmap = it.getParcelableExtra("data");
                myImage.setImageBitmap(bitmap);
                if (bitmap != null) {
                    String fileName = "headphoto" + "_"
                            + System.currentTimeMillis() + 0 + ".jpg";

                    String filePath = FileUtils
                            .saveBitmapFileWithFormat(bitmap, fileName, ".jpg");
                    request(filePath);
                }
            }
        }
        if (requestCode == AUTO_REQUEST) {
            //   presenter.getIntent(null);
        }

    }


    public void request(String path) {

        File imageFile = ImageUtils.getSmallImageFile(getApplicationContext(), path, 150, 150,
                true);
        if (null != imageFile && imageFile.length() > 0) {
            String filePath = imageFile.getPath();
            //   presenter.loadMoreData(filePath);
        } else {
            showToast("选择图片失败");
        }
    }


    // 裁剪图片的方法
    private void crop(Uri uri) {
        // 裁剪图片意图
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // 裁剪框的比例，1：1
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // 裁剪后输出图片的尺寸大小
        intent.putExtra("outputX", 250);
        intent.putExtra("outputY", 250);
        // 图片格式
        intent.putExtra("outputFormat", "JPEG");
        intent.putExtra("noFaceDetection", true);// 取消人脸识别
        intent.putExtra("return-data", true);// true:不返回uri，false：返回uri
        toActivity(intent, PHOTO_REQUEST_CUT);
    }


}
